// 文章 reducer 模块

import { ArticleDetail } from '@/types/data';
import { ArticleAction } from '@/types/store';
// 导入dayjs
import dayjs from 'dayjs';
// 导入本地化格式插件
import localizedFormat from 'dayjs/plugin/localizedFormat';
dayjs.extend(localizedFormat);

// 文章模块的类型
type ArticleState = {
  detail: ArticleDetail;
};

// 文章模块数据
const initialState = {
  detail: {},
} as ArticleState;

export const article = (
  state = initialState,
  action: ArticleAction
): ArticleState => {
  // 处理文章详情数据
  if (action.type === 'article/getArticleById') {
    return {
      ...state,
      detail: {
        ...action.payload,
        // UI 显示需求处理
        pubdate: dayjs(action.payload.pubdate).locale('zh-cn').format('LL'),
      },
    };
  }

  // 处理关注/取消关注、收藏、点赞
  if (action.type === 'article/updateInfo') {
    return {
      ...state,
      detail: {
        ...state.detail,
        [action.payload.name]: action.payload.value,
      },
    };
  }

  return state;
};
